package org.langqiao.thread;
import java.awt.*;
//import java.awt.Event.*;
import javax.swing.*;
//import javax.swing.event.*;

class CardBuffer {
	private int value;//value是否空的信号量
	private boolean isEmpty=true;
	private int order=0;//信号量约定取牌线程的次序
	synchronized void put(int i)
	{
		while(!isEmpty)
		try
		{
				this.wait();
		}
		catch(InterruptedException e){}
			value=i;//设置value为不空状态
			isEmpty=false;
			notifyAll();//唤醒所有其他等待的线程
	}
	synchronized int get(int order)//order是取牌线程约定的次序
	{
		while(isEmpty||this.order!=order)//当value为空，或者是取牌顺序与其不符时等待
			try
		{
				this.wait();
		}
		catch(InterruptedException e){};
		isEmpty=true;//设置value为空状态，并返回值
		notifyAll();
		this.order=(this.order+1)%4;//加1，使取牌顺序轮转
		return value;
	}
}
class Sender extends Thread{//发牌线程类
	private CardBuffer cardbuffer;
	private int count;

	public Sender(CardBuffer cardbuffer, int count){// 构造函数
		this.cardbuffer = cardbuffer;
		this.count = count;
	}

	public void run() {
		for (int i = 1; i <= this.count; i++)
			cardbuffer.put(i);
	}
	    
}
class Receiver extends Thread{//取牌线程类

	private CardBuffer cardbuffer;
	private JTextArea text;
	private int order;// 信号量，约定取牌线程的次序

	public Receiver(CardBuffer cardbuffer, JTextArea text, int order) {
		this.cardbuffer = cardbuffer;
		this.text = text;
		this.order = order;
	}

	public void run() {
		while (true) {
			text.append("" + cardbuffer.get(this.order));
			try {
				this.sleep(100);
			} catch (InterruptedException e) {
			} finally {
			}
		}
	}
}
public class  CardJFrame extends JFrame{
	public CardJFrame() {
		super("取牌程序");
		this.setBounds(400, 300, 400, 300);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container container = this.getContentPane();
		container.setLayout(new GridLayout(3, 3));// 3行3列网格布局
		container.add(new JPanel());// 网格布局的第一行第一列
		JTextArea text[] = new JTextArea[4];// 显示牌号的四个文本区
		Font font = new Font("Helvetica", Font.PLAIN, 16);
		for (int i = 0; i < text.length; i++) {
			text[i] = new JTextArea();
			text[i].setLineWrap(true);// 设置文本区自动换行
			text[i].setEditable(false);// 不可编辑
			text[i].setFont(font);
			container.add(text[i]);
			container.add(new JPanel());

		}
		this.setVisible(true);
		CardBuffer cardbuffer = new CardBuffer();
		Sender s = new Sender(cardbuffer, 52);
		s.setPriority(10);// 设置最高优先级
		s.start();// 发牌线程开始执行
		for (int i = 0; i < text.length; i++)
			(new Receiver(cardbuffer, text[i], i)).start();// 创建并启动4个取牌的线程，优先级为5

	}

	public static void main(String[] args) {
		new CardJFrame();
	}
}
